package com.campus.controller;

import com.campus.entity.User;
import com.campus.service.UserService;
import com.campus.util.JwtUtils;
import com.campus.web.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseResult login(@RequestParam String loginName, @RequestParam String password) {
        User user = userService.login(loginName, password);
        if (user != null) {
            Map<String, Object> response = new HashMap<>();
            response.put("user", user);
            // 生成JWT令牌，并将用户信息（通常是用户ID或用户名）作为载荷的一部分
            String jwtToken = JwtUtils.generateToken(user.getId()); // 假设user有一个getId()方法返回唯一标识符
            response.put("token", jwtToken);
            return ResponseResult.ok(response,"登录成功");
        } else {
            return ResponseResult.error(HttpStatus.BAD_REQUEST,"登录失败");
        }
    }

    @PostMapping("/register")
    public ResponseResult<User> register(@RequestBody User user) {
        userService.register(user);
        return ResponseResult.ok("添加成功");
    }

    @GetMapping("/search")
    public ResponseResult<List<User>> searchUserByNameOrId( String loginName, Integer id ) {
        List<User> users = userService.searchUserByNameOrId(loginName, id);
        if (!users.isEmpty()) {
            return ResponseResult.ok(users,"查询成功");
        } else {
            return ResponseResult.error(HttpStatus.BAD_REQUEST,"查询失败");
        }
    }
}